package com.zenith.common.util;

import com.zenith.common.constant.CommonConstant;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * 用户上下文工具类
 */
public class UserContextUtil {

    /**
     * 获取当前用户ID
     */
    public static Long getCurrentUserId() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            Object userId = request.getAttribute(CommonConstant.USER_ID);
            return userId != null ? Long.valueOf(userId.toString()) : null;
        }
        return null;
    }

    /**
     * 获取当前用户角色
     */
    public static String getCurrentUserRole() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            Object userRole = request.getAttribute(CommonConstant.USER_ROLE);
            return userRole != null ? userRole.toString() : null;
        }
        return null;
    }

    /**
     * 获取当前用户名
     */
    public static String getCurrentUsername() {
        HttpServletRequest request = getCurrentRequest();
        if (request != null) {
            Object username = request.getAttribute(CommonConstant.USERNAME);
            return username != null ? username.toString() : null;
        }
        return null;
    }

    /**
     * 获取当前请求
     */
    private static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }
}